import request from '@/utils/request'
import axios from 'axios'

// 模拟数据
const mockData = [
  {
    id: 1,
    traceabilityCode: 'TR20210718001',
    productName: '兔肉(小)',
    productionBatch: '2021-07-18',
    shelfLife: 12,
    productionLicenseNumber: 'SC12345678901',
    productionCompany: '成都爱吃兔食品加工有限公司',
    coverImage: '',
    completenessScore: 80,
    createTime: '2021-07-18',
    updateTime: null,
    isDeleted: 0
  },
  {
    id: 2,
    traceabilityCode: 'TR20210718002',
    productName: '兔肉(大)',
    productionBatch: '2021-07-18',
    shelfLife: 12,
    productionLicenseNumber: 'SC12345678902',
    productionCompany: '成都爱吃兔食品加工有限公司',
    coverImage: '',
    completenessScore: 60,
    createTime: '2021-07-18',
    updateTime: null,
    isDeleted: 0
  },
  {
    id: 3,
    traceabilityCode: 'TR20210718003',
    productName: '兔肚丝',
    productionBatch: '2021-07-18',
    shelfLife: 12,
    productionLicenseNumber: 'SC12345678903',
    productionCompany: '成都爱吃兔食品加工有限公司',
    coverImage: '',
    completenessScore: 100,
    createTime: '2021-07-18',
    updateTime: null,
    isDeleted: 0
  },
  {
    id: 4,
    traceabilityCode: 'TR20210718004',
    productName: '兔肝丁',
    productionBatch: '2021-07-18',
    shelfLife: 12,
    productionLicenseNumber: 'SC12345678904',
    productionCompany: '成都爱吃兔食品加工有限公司',
    coverImage: '',
    completenessScore: 80,
    createTime: '2021-07-18',
    updateTime: null,
    isDeleted: 0
  },
  {
    id: 5,
    traceabilityCode: 'TR20210718005',
    productName: '冰冻兔',
    productionBatch: '2021-07-18',
    shelfLife: 12,
    productionLicenseNumber: 'SC12345678905',
    productionCompany: '成都爱吃兔食品加工有限公司',
    coverImage: '',
    completenessScore: 100,
    createTime: '2021-07-18',
    updateTime: null,
    isDeleted: 0
  },
  {
    id: 6,
    traceabilityCode: 'TR20210718006',
    productName: '兔头(原味)',
    productionBatch: '2021-07-18',
    shelfLife: 12,
    productionLicenseNumber: 'SC12345678906',
    productionCompany: '成都爱吃兔食品加工有限公司',
    coverImage: '',
    completenessScore: 100,
    createTime: '2021-07-18',
    updateTime: null,
    isDeleted: 0
  },
  {
    id: 7,
    traceabilityCode: 'TR20210718007',
    productName: '兔头(麻辣)',
    productionBatch: '2021-07-18',
    shelfLife: 12,
    productionLicenseNumber: 'SC12345678907',
    productionCompany: '成都爱吃兔食品加工有限公司',
    coverImage: '',
    completenessScore: 100,
    createTime: '2021-07-18',
    updateTime: null,
    isDeleted: 0
  }
]

// 是否使用模拟数据
const useMockData = false

// 后端API基础URL
const API_BASE_URL = 'http://localhost:5203/api'

// 模拟API响应
const mockResponse = (data, delay = 500) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        code: 'Success',
        message: '操作成功',
        data
      })
    }, delay)
  })
}

// 添加时间戳防止缓存
const addTimestamp = (url) => {
  const separator = url.includes('?') ? '&' : '?'
  return `${url}${separator}_t=${new Date().getTime()}`
}

// 创建新的axios实例，专门用于直接调用
const directApi = axios.create({
  baseURL: API_BASE_URL,
  timeout: 15000,
  headers: {
    'Content-Type': 'application/json;charset=utf-8',
    'Cache-Control': 'no-cache',
    'Pragma': 'no-cache'
  }
})

// 响应拦截器
directApi.interceptors.response.use(
  response => {
    const res = response.data
    console.log('API原始响应:', res)
    
    // 如果数据已经包含正确格式，直接返回
    if (res.code === 'Success' || res.code === 0 || res.code === 200) {
      // 不同数据结构的处理
      if (res.data && res.data.items && Array.isArray(res.data.items)) {
        // 确保列表项有必要的属性
        res.data.items = res.data.items.map(item => ({
          ...item,
          id: item.id || 0,
          productName: item.productName || '',
          productionBatch: item.productionBatch || '',
          shelfLife: item.shelfLife || 0,
          productionLicenseNumber: item.productionLicenseNumber || '',
          productionCompany: item.productionCompany || '',
          completenessScore: item.completenessScore || 0
        }))
      } else if (res.data && Array.isArray(res.data)) {
        // 将数组转换为标准分页格式
        const items = res.data.map(item => ({
          ...item,
          id: item.id || 0,
          productName: item.productName || '',
          productionBatch: item.productionBatch || '',
          shelfLife: item.shelfLife || 0,
          productionLicenseNumber: item.productionLicenseNumber || '',
          productionCompany: item.productionCompany || '',
          completenessScore: item.completenessScore || 0
        }))
        res.data = { 
          items: items,
          totalCount: items.length
        }
      }
      return res
    } else if (response.status === 200) {
      // 如果直接返回了原始数据但没有标准结构，进行转换
      console.log('API返回的不是标准结构，尝试转换')
      return {
        code: 'Success',
        message: '操作成功',
        data: res
      }
    }
    
    // 其他情况作为错误返回
    return Promise.reject(new Error(res.message || '请求失败'))
  },
  error => {
    console.error('API请求错误:', error)
    return Promise.reject(error)
  }
)

// 溯源管理API
export const traceabilityApi = {
  // 获取溯源管理列表(分页)
  getPagedList(params) {
    if (useMockData) {
      // 过滤数据
      let filteredData = mockData.filter(item => item.isDeleted === 0)

      // 应用筛选条件
      if (params.productName) {
        filteredData = filteredData.filter(item => item.productName.includes(params.productName))
      }
      if (params.productionBatchStart) {
        filteredData = filteredData.filter(item => item.productionBatch >= params.productionBatchStart)
      }
      if (params.productionBatchEnd) {
        filteredData = filteredData.filter(item => item.productionBatch <= params.productionBatchEnd)
      }
      if (params.shelfLifeMin) {
        filteredData = filteredData.filter(item => item.shelfLife >= params.shelfLifeMin)
      }
      if (params.shelfLifeMax) {
        filteredData = filteredData.filter(item => item.shelfLife <= params.shelfLifeMax)
      }
      if (params.productionLicenseNumber) {
        filteredData = filteredData.filter(item => item.productionLicenseNumber.includes(params.productionLicenseNumber))
      }
      if (params.productionCompany) {
        filteredData = filteredData.filter(item => item.productionCompany.includes(params.productionCompany))
      }

      // 计算总数
      const total = filteredData.length

      // 分页
      const start = (params.pageIndex - 1) * params.pageSize
      const end = start + params.pageSize
      const pagedData = filteredData.slice(start, end)

      // 返回模拟响应
      return mockResponse({
        items: pagedData,
        pageIndex: params.pageIndex,
        pageSize: params.pageSize,
        totalCount: total,
        totalPages: Math.ceil(total / params.pageSize)
      })
    }

    // 使用新的直接API请求
    console.log('发送溯源分页请求:', params)
    // 确保路径与后端控制器路由匹配
    return directApi.get(addTimestamp('/Traceability/paged'), { params })
      .then(response => {
        console.log('原始响应数据:', response)
        // 确保返回的是API期望的格式
        if (response && response.code === 'Success') {
          return response
        } else {
          // 如果响应结构不符合预期，尝试转换
          return {
            code: 'Success',
            message: '获取溯源管理记录分页数据成功',
            data: {
              items: Array.isArray(response.data) ? response.data : (response.data?.items || []),
              totalCount: response.data?.totalCount || response.data?.total || 0,
              pageIndex: params.pageIndex,
              pageSize: params.pageSize
            }
          }
        }
      })
      .catch(error => {
        console.error('溯源分页请求失败:', error)
        throw error
      })
  },
  
  // 获取所有溯源管理记录
  getAll() {
    if (useMockData) {
      return mockResponse(mockData.filter(item => item.isDeleted === 0))
    }

    return directApi.get(addTimestamp('/Traceability'))
      .catch(error => {
        console.error('获取所有溯源请求失败:', error)
        throw error
      })
  },
  
  // 根据ID获取单条记录
  getById(id) {
    console.log('调用getById API, ID:', id)
    
    if (useMockData) {
      const item = mockData.find(item => item.id === id && item.isDeleted === 0)
      console.log('使用模拟数据, 结果:', item)
      return mockResponse(item || null)
    }

    console.log(`发送获取详情请求: /Traceability/${id}`)
    return directApi.get(addTimestamp(`/Traceability/${id}`))
      .then(response => {
        console.log(`获取ID=${id}详情成功:`, response)
        
        // 检查响应结构并确保返回数据符合预期
        if (response && response.data) {
          // 确保数据有必要的字段
          const data = {
            id: response.data.id || id,
            traceabilityCode: response.data.traceabilityCode || '',
            productName: response.data.productName || '',
            productionBatch: response.data.productionBatch || '',
            shelfLife: response.data.shelfLife || 30,
            productionLicenseNumber: response.data.productionLicenseNumber || '',
            productionCompany: response.data.productionCompany || '',
            coverImage: response.data.coverImage || '',
            completenessScore: response.data.completenessScore || 0
          }
          
          // 更新响应中的数据
          response.data = data
        }
        
        return response
      })
      .catch(error => {
        console.error(`获取溯源ID=${id}请求失败:`, error)
        
        // 捕获错误但不抛出，让上层组件处理
        if (error.response) {
          console.error('错误状态:', error.response.status)
          console.error('错误数据:', error.response.data)
        }
        
        // 返回一个友好的错误响应而不是抛出异常
        return {
          code: 'Error',
          message: `获取ID=${id}的数据失败`,
          data: null
        }
      })
  },
  
  // 根据溯源码获取记录
  getByCode(code) {
    if (useMockData) {
      const item = mockData.find(item => item.traceabilityCode === code && item.isDeleted === 0)
      return mockResponse(item || null)
    }

    return directApi.get(addTimestamp(`/Traceability/code/${code}`))
      .catch(error => {
        console.error(`获取溯源码=${code}请求失败:`, error)
        throw error
      })
  },
  
  // 创建溯源记录
  create(data) {
    if (useMockData) {
      // 生成新ID
      const newId = Math.max(...mockData.map(item => item.id)) + 1
      
      // 创建新记录
      const newItem = {
        ...data,
        id: newId,
        traceabilityCode: `TR${new Date().toISOString().slice(0, 10).replace(/-/g, '')}${newId.toString().padStart(3, '0')}`,
        createTime: new Date().toISOString().slice(0, 10),
        updateTime: null,
        isDeleted: 0
      }
      
      // 添加到模拟数据
      mockData.push(newItem)
      
      return mockResponse(newItem)
    }

    return directApi.post(addTimestamp('/Traceability'), data)
      .catch(error => {
        console.error('创建溯源记录失败:', error)
        throw error
      })
  },
  
  // 更新溯源记录
  update(id, data) {
    console.log('调用update API, ID:', id, '数据:', data)
    
    if (useMockData) {
      const index = mockData.findIndex(item => item.id === id)
      if (index !== -1) {
        // 更新记录
        mockData[index] = {
          ...mockData[index],
          ...data,
          updateTime: new Date().toISOString().slice(0, 10)
        }
        console.log('使用模拟数据更新, 结果:', mockData[index])
        return mockResponse(mockData[index])
      }
      console.log('模拟数据中未找到ID:', id)
      return mockResponse(null)
    }

    // 确保数据对象包含必要字段
    const updatedData = {
      ...data,
      id: id
    }
    
    console.log(`发送更新请求: /Traceability/${id}`)
    return directApi.put(addTimestamp(`/Traceability/${id}`), updatedData)
      .then(response => {
        console.log(`更新ID=${id}成功:`, response)
        return response
      })
      .catch(error => {
        console.error(`更新溯源记录ID=${id}失败:`, error)
        
        // 详细记录错误信息
        if (error.response) {
          console.error('错误状态:', error.response.status)
          console.error('错误数据:', error.response.data)
        }
        
        // 返回友好错误而不是抛出异常
        return {
          code: 'Error',
          message: `更新ID=${id}的数据失败: ${error.message || '未知错误'}`,
          data: null
        }
      })
  },
  
  // 删除溯源记录
  delete(id) {
    console.log('调用delete API, ID:', id)
    
    if (useMockData) {
      const index = mockData.findIndex(item => item.id === id)
      if (index !== -1) {
        // 逻辑删除
        mockData[index].isDeleted = 1
        mockData[index].updateTime = new Date().toISOString().slice(0, 10)
        console.log('使用模拟数据删除成功, ID:', id)
        return mockResponse(true)
      }
      console.log('模拟数据中未找到ID:', id)
      return mockResponse(false)
    }

    console.log(`发送删除请求: /Traceability/${id}`)
    return directApi.delete(addTimestamp(`/Traceability/${id}`))
      .then(response => {
        console.log(`删除ID=${id}成功:`, response)
        return response
      })
      .catch(error => {
        console.error(`删除溯源记录ID=${id}失败:`, error)
        
        // 详细记录错误信息
        if (error.response) {
          console.error('错误状态:', error.response.status)
          console.error('错误数据:', error.response.data)
        }
        
        // 返回友好错误而不是抛出异常
        return {
          code: 'Error',
          message: `删除ID=${id}的数据失败: ${error.message || '未知错误'}`,
          data: null
        }
      })
  },
  
  // 批量删除溯源记录
  batchDelete(ids) {
    console.log('调用batchDelete API, IDs:', ids)
    
    if (useMockData) {
      ids.forEach(id => {
        const index = mockData.findIndex(item => item.id === id)
        if (index !== -1) {
          // 逻辑删除
          mockData[index].isDeleted = 1
          mockData[index].updateTime = new Date().toISOString().slice(0, 10)
        }
      })
      console.log('使用模拟数据批量删除成功')
      return mockResponse(true)
    }

    console.log(`发送批量删除请求: /Traceability/batch-delete, IDs:`, ids)
    return directApi.post(addTimestamp('/Traceability/batch-delete'), ids)
      .then(response => {
        console.log(`批量删除成功:`, response)
        return response
      })
      .catch(error => {
        console.error('批量删除溯源记录失败:', error)
        
        // 详细记录错误信息
        if (error.response) {
          console.error('错误状态:', error.response.status)
          console.error('错误数据:', error.response.data)
        }
        
        // 返回友好错误而不是抛出异常
        return {
          code: 'Error',
          message: `批量删除数据失败: ${error.message || '未知错误'}`,
          data: null
        }
      })
  }
} 